from utility import *



def find_most_suitable_server(servers):
    result = servers[0]
    for i in range(1, len(servers)):
        if result.max_utilization() > servers[i].max_utilization() \
            or result.balance_ratio() > servers[i].balance_ratio():
            result = servers[i]
    return result



def find_potential_task(server, tasks):
    status = False
    result = None
    for t in tasks:
        if status == False:
            if server.check_resource_limit(t):
                status = True
                result = t
        else:
            if result.max_demand() < t.max_demand() and \
                server.check_resource_limit(t):
                result = t
    return result



def max_bru(tasks):
    servers = []
    while len(tasks) != 0:
        status = False
        if len(servers) != 0:
            server = find_most_suitable_server(servers)
            task = find_potential_task(server, tasks)
            if task != None:
                server.add_task(task)
                tasks.remove(task)
                status = True

        if status == False:
            new_server = create_sample_server()
            new_server.add_task(tasks.pop())
            servers.append(new_server)

    return servers